home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / samba.idb / usr / samba / src / source / password.c.z / password.c
Encoding:
C/C++ Source or Header  |  1998-10-28  |  47.8 KB  |  1,769 lines

  1. /* 
  2.    Unix SMB/Netbios implementation.
  3.    Version 1.9.
  4.    Password and authentication handling
  5.    Copyright (C) Andrew Tridgell 1992-1998
  6.    
  7.    This program is free software; you can redistribute it and/or modify
  8.    it under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 2 of the License, or
  10.    (at your option) any later version.
  11.    
  12.    This program is distributed in the hope that it will be useful,
  13.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.    GNU General Public License for more details.
  16.    
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21.  
  22. #include "includes.h"
  23.  
  24. #if (defined(NETGROUP) && defined (AUTOMOUNT))
  25. #include "rpcsvc/ypclnt.h"
  26. #endif
  27.  
  28. extern int DEBUGLEVEL;
  29. extern int Protocol;
  30.  
  31. /* users from session setup */
  32. static pstring session_users="";
  33.  
  34. /* these are kept here to keep the string_combinations function simple */
  35. static char this_user[100]="";
  36. static char this_salt[100]="";
  37. static char this_crypted[100]="";
  38.  
  39. /* Data to do lanman1/2 password challenge. */
  40. static unsigned char saved_challenge[8];
  41. static BOOL challenge_sent=False;
  42.  
  43. /*******************************************************************
  44. Get the next challenge value - no repeats.
  45. ********************************************************************/
  46. void generate_next_challenge(char *challenge)
  47. {
  48.     unsigned char buf[16];
  49.     static int counter = 0;
  50.     struct timeval tval;
  51.     int v1,v2;
  52.  
  53.     /* get a sort-of random number */
  54.     GetTimeOfDay(&tval);
  55.     v1 = (counter++) + getpid() + tval.tv_sec;
  56.     v2 = (counter++) * getpid() + tval.tv_usec;
  57.     SIVAL(challenge,0,v1);
  58.     SIVAL(challenge,4,v2);
  59.  
  60.     /* mash it up with md4 */
  61.     mdfour(buf, (unsigned char *)challenge, 8);
  62.  
  63.     memcpy(saved_challenge, buf, 8);
  64.     memcpy(challenge,buf,8);
  65.     challenge_sent = True;
  66. }
  67.  
  68. /*******************************************************************
  69. set the last challenge sent, usually from a password server
  70. ********************************************************************/
  71. BOOL set_challenge(char *challenge)
  72. {
  73.   memcpy(saved_challenge,challenge,8);
  74.   challenge_sent = True;
  75.   return(True);
  76. }
  77.  
  78. /*******************************************************************
  79. get the last challenge sent
  80. ********************************************************************/
  81. BOOL last_challenge(char *challenge)
  82. {
  83.   if (!challenge_sent) return(False);
  84.   memcpy(challenge,saved_challenge,8);
  85.   return(True);
  86. }
  87.  
  88. /* this holds info on user ids that are already validated for this VC */
  89. static user_struct *validated_users = NULL;
  90. static int num_validated_users = 0;
  91.  
  92. /****************************************************************************
  93. check if a uid has been validated, and return an pointer to the user_struct
  94. if it has. NULL if not. vuid is biased by an offset. This allows us to
  95. tell random client vuid's (normally zero) from valid vuids.
  96. ****************************************************************************/
  97. user_struct *get_valid_user_struct(uint16 vuid)
  98. {
  99.   if (vuid == UID_FIELD_INVALID)
  100.     return NULL;
  101.   vuid -= VUID_OFFSET;
  102.   if ((vuid >= (uint16)num_validated_users) || 
  103.      (validated_users[vuid].uid == -1) || (validated_users[vuid].gid == -1))
  104.     return NULL;
  105.   return &validated_users[vuid];
  106. }
  107.  
  108. /****************************************************************************
  109. invalidate a uid
  110. ****************************************************************************/
  111. void invalidate_vuid(uint16 vuid)
  112. {
  113.   user_struct *vuser = get_valid_user_struct(vuid);
  114.  
  115.   if (vuser == NULL) return;
  116.  
  117.   vuser->uid = -1;
  118.   vuser->gid = -1;
  119.  
  120.   vuser->n_sids = 0;
  121.  
  122.   /* same number of igroups as groups as attrs */
  123.   vuser->n_groups = 0;
  124.  
  125.   if (vuser->groups && (vuser->groups != (gid_t *)vuser->igroups))
  126.        free(vuser->groups);
  127.  
  128.   if (vuser->igroups) free(vuser->igroups);
  129.   if (vuser->attrs  ) free(vuser->attrs);
  130.   if (vuser->sids   ) free(vuser->sids);
  131.  
  132.   vuser->attrs   = NULL;
  133.   vuser->sids    = NULL;
  134.   vuser->igroups = NULL;
  135.   vuser->groups  = NULL;
  136. }
  137.  
  138.  
  139. /****************************************************************************
  140. return a validated username
  141. ****************************************************************************/
  142. char *validated_username(uint16 vuid)
  143. {
  144.   user_struct *vuser = get_valid_user_struct(vuid);
  145.   if (vuser == NULL)
  146.     return 0;
  147.   return(vuser->name);
  148. }
  149.  
  150. /****************************************************************************
  151. register a uid/name pair as being valid and that a valid password
  152. has been given. vuid is biased by an offset. This allows us to
  153. tell random client vuid's (normally zero) from valid vuids.
  154. ****************************************************************************/
  155. uint16 register_vuid(int uid,int gid, char *unix_name, char *requested_name, BOOL guest)
  156. {
  157.   user_struct *vuser;
  158.   struct passwd *pwfile; /* for getting real name from passwd file */
  159.  
  160.   /* Ensure no vuid gets registered in share level security. */
  161.   if(lp_security() == SEC_SHARE)
  162.     return UID_FIELD_INVALID;
  163.  
  164. #if 0
  165.   /*
  166.    * After observing MS-Exchange services writing to a Samba share
  167.    * I belive this code is incorrect. Each service does its own
  168.    * sessionsetup_and_X for the same user, and as each service shuts
  169.    * down, it does a user_logoff_and_X. As we are consolidating multiple
  170.    * sessionsetup_and_X's onto the same vuid here, when the first service
  171.    * shuts down, it invalidates all the open files for the other services.
  172.    * Hence I am removing this code and forcing each sessionsetup_and_X
  173.    * to get a new vuid.
  174.    * Jeremy Allison. (jallison@whistle.com).
  175.    */
  176.  
  177.   int i;
  178.   for(i = 0; i < num_validated_users; i++) {
  179.     vuser = &validated_users[i];
  180.     if ( vuser->uid == uid )
  181.       return (uint16)(i + VUID_OFFSET); /* User already validated */
  182.   }
  183. #endif
  184.  
  185.   validated_users = (user_struct *)Realloc(validated_users,
  186.                sizeof(user_struct)*
  187.                (num_validated_users+1));
  188.   
  189.   if (!validated_users)
  190.     {
  191.       DEBUG(0,("Failed to realloc users struct!\n"));
  192.       num_validated_users = 0;
  193.       return UID_FIELD_INVALID;
  194.     }
  195.  
  196.   vuser = &validated_users[num_validated_users];
  197.   num_validated_users++;
  198.  
  199.   vuser->uid = uid;
  200.   vuser->gid = gid;
  201.   vuser->guest = guest;
  202.   fstrcpy(vuser->name,unix_name);
  203.   fstrcpy(vuser->requested_name,requested_name);
  204.  
  205.   vuser->n_sids = 0;
  206.   vuser->sids   = NULL;
  207.  
  208.   vuser->n_groups = 0;
  209.   vuser->groups  = NULL;
  210.   vuser->igroups = NULL;
  211.   vuser->attrs    = NULL;
  212.  
  213.   /* Find all the groups this uid is in and store them. 
  214.      Used by become_user() */
  215.   setup_groups(unix_name,uid,gid,
  216.            &vuser->n_groups,
  217.            &vuser->igroups,
  218.            &vuser->groups,
  219.            &vuser->attrs);
  220.  
  221.   DEBUG(3,("uid %d registered to name %s\n",uid,unix_name));
  222.  
  223.   DEBUG(3, ("Clearing default real name\n"));
  224.   fstrcpy(vuser->real_name, "<Full Name>\0");
  225.   if (lp_unix_realname()) {
  226.     if ((pwfile=getpwnam(vuser->name))!= NULL)
  227.       {
  228.       DEBUG(3, ("User name: %s\tReal name: %s\n",vuser->name,pwfile->pw_gecos));
  229.       fstrcpy(vuser->real_name, pwfile->pw_gecos);
  230.       }
  231.   }
  232.  
  233.   return (uint16)((num_validated_users - 1) + VUID_OFFSET);
  234. }
  235.  
  236.  
  237. /****************************************************************************
  238. add a name to the session users list
  239. ****************************************************************************/
  240. void add_session_user(char *user)
  241. {
  242.   fstring suser;
  243.   StrnCpy(suser,user,sizeof(suser)-1);
  244.  
  245.   if (!Get_Pwnam(suser,True)) return;
  246.  
  247.   if (suser && *suser && !in_list(suser,session_users,False))
  248.     {
  249.       if (strlen(suser) + strlen(session_users) + 2 >= sizeof(pstring))
  250.     DEBUG(1,("Too many session users??\n"));
  251.       else
  252.     {
  253.       pstrcat(session_users," ");
  254.       pstrcat(session_users,suser);
  255.     }
  256.     }
  257. }
  258.  
  259.  
  260. #ifdef NO_GETSPNAM
  261. /* a fake shadow password routine which just fills a fake spwd struct
  262.  * with the sp_pwdp field. (sreiz@aie.nl)
  263.  */
  264. static struct spwd *getspnam(char *username) /* fake shadow password routine */
  265. {
  266.        FILE *f;
  267.        char line[1024];
  268.        static char pw[20];
  269.        static struct spwd static_spwd;
  270.  
  271.        static_spwd.sp_pwdp=0;
  272.        if (!(f=fopen("/etc/master.passwd", "r")))
  273.                return 0;
  274.        while (fgets(line, 1024, f)) {
  275.                if (!strncmp(line, username, strlen(username)) &&
  276.                 line[strlen(username)]==':') { /* found entry */
  277.                        char *p, *q;
  278.  
  279.                        p=line+strlen(username)+1;
  280.                        if ((q=strchr(p, ':'))) {
  281.                                *q=0;
  282.                                if (q-p+1>20)
  283.                                        break;
  284.                                safe_strcpy(pw, p, sizeof(pw)-1);
  285.                                static_spwd.sp_pwdp=pw;
  286.                        }
  287.                        break;
  288.                }
  289.        }
  290.        fclose(f);
  291.        if (static_spwd.sp_pwdp)
  292.                return &static_spwd;
  293.        return 0;
  294. }
  295. #endif
  296.  
  297.  
  298. #ifdef OSF1_ENH_SEC
  299. /****************************************************************************
  300. an enhanced crypt for OSF1
  301. ****************************************************************************/
  302. static char *osf1_bigcrypt(char *password,char *salt1)
  303. {
  304.   static char result[AUTH_MAX_PASSWD_LENGTH] = "";
  305.   char *p1;
  306.   char *p2=password;
  307.   char salt[3];
  308.   int i;
  309.   int parts = strlen(password) / AUTH_CLEARTEXT_SEG_CHARS;
  310.   if (strlen(password)%AUTH_CLEARTEXT_SEG_CHARS)
  311.     parts++;
  312.  
  313.   StrnCpy(salt,salt1,2);
  314.   StrnCpy(result,salt1,2);
  315.  
  316.   for (i=0; i<parts;i++)
  317.     {
  318.       p1 = crypt(p2,salt);
  319.       safe_strcat(result,p1+2,sizeof(result)-1);
  320.       StrnCpy(salt,&result[2+i*AUTH_CIPHERTEXT_SEG_CHARS],2);
  321.       p2 += AUTH_CLEARTEXT_SEG_CHARS;
  322.     }
  323.  
  324.   return(result);
  325. }
  326. #endif
  327.  
  328. /****************************************************************************
  329. update the encrypted smbpasswd file from the plaintext username and password
  330. *****************************************************************************/
  331. BOOL update_smbpassword_file( struct passwd *pass, fstring password)
  332. {
  333.   struct smb_passwd smbpw;
  334.   BOOL ret;
  335.  
  336.   /* Fake up an smb_passwd. */
  337.   smbpw.smb_userid = pass->pw_uid;
  338.   smbpw.smb_name = pass->pw_name;
  339.   smbpw.smb_passwd = NULL;
  340.   smbpw.smb_nt_passwd = NULL;
  341.   smbpw.acct_ctrl = ACB_NORMAL;
  342.  
  343.   /* Here, the flag is one, because we want to ignore the XXXXXXX'd out password */
  344.   ret = change_oem_password( &smbpw, password, 1);
  345.   if (ret == False)
  346.     DEBUG(3,("update_smbpasswd_entry: change_oem_password returned False\n"));
  347.  
  348.   return ret;
  349. }
  350.  
  351. /****************************************************************************
  352. update the enhanced security database. Only relevant for OSF1 at the moment.
  353. ****************************************************************************/
  354. static void update_protected_database( char *user, BOOL result)
  355. {
  356. #ifdef OSF1_ENH_SEC
  357.   struct pr_passwd *mypasswd;
  358.   time_t starttime;
  359.  
  360.   mypasswd = getprpwnam (user);
  361.   starttime = time (NULL);
  362.  
  363.   if (result)
  364.     {
  365.       mypasswd->ufld.fd_slogin = starttime;
  366.       mypasswd->ufld.fd_nlogins = 0;
  367.       
  368.       putprpwnam(user,mypasswd);
  369.       
  370.       DEBUG(3,("Update protected database for Account %s after succesful connection\n",user));
  371.     }
  372.   else
  373.     {
  374.       mypasswd->ufld.fd_ulogin = starttime;
  375.       mypasswd->ufld.fd_nlogins = mypasswd->ufld.fd_nlogins + 1;
  376.       if ( mypasswd->ufld.fd_max_tries != 0 && mypasswd->ufld.fd_nlogins > mypasswd->ufld.fd_max_tries )
  377.     {
  378.       mypasswd->uflg.fg_lock = 0;
  379.       DEBUG(3,("Account is disabled -- see Account Administrator.\n"));
  380.     }
  381.       putprpwnam ( user , mypasswd );
  382.       DEBUG(3,("Update protected database for Account %s after refusing connection\n",user));
  383.     }
  384. #else
  385.   DEBUG(6,("Updated database with %s %s\n",user,BOOLSTR(result)));
  386. #endif
  387. }
  388.  
  389.  
  390. #ifdef USE_PAM
  391. /*******************************************************************
  392. check on PAM authentication
  393. ********************************************************************/
  394.  
  395. /* We first need some helper functions */
  396. #include <security/pam_appl.h>
  397. /* Static variables used to communicate between the conversation function
  398.  * and the server_login function
  399.  */
  400. static char *PAM_username;
  401. static char *PAM_password;
  402.  
  403. /* PAM conversation function
  404.  * Here we assume (for now, at least) that echo on means login name, and
  405.  * echo off means password.
  406.  */
  407. static int PAM_conv (int num_msg,
  408.                      const struct pam_message **msg,
  409.                      struct pam_response **resp,
  410.                      void *appdata_ptr) {
  411.   int replies = 0;
  412.   struct pam_response *reply = NULL;
  413.  
  414.   #define COPY_STRING(s) (s) ? strdup(s) : NULL
  415.  
  416.   reply = malloc(sizeof(struct pam_response) * num_msg);
  417.   if (!reply) return PAM_CONV_ERR;
  418.  
  419.   for (replies = 0; replies < num_msg; replies++) {
  420.     switch (msg[replies]->msg_style) {
  421.       case PAM_PROMPT_ECHO_ON:
  422.         reply[replies].resp_retcode = PAM_SUCCESS;
  423.         reply[replies].resp = COPY_STRING(PAM_username);
  424.           /* PAM frees resp */
  425.         break;
  426.       case PAM_PROMPT_ECHO_OFF:
  427.         reply[replies].resp_retcode = PAM_SUCCESS;
  428.         reply[replies].resp = COPY_STRING(PAM_password);
  429.           /* PAM frees resp */
  430.         break;
  431.       case PAM_TEXT_INFO:
  432.     /* fall through */
  433.       case PAM_ERROR_MSG:
  434.         /* ignore it... */
  435.         reply[replies].resp_retcode = PAM_SUCCESS;
  436.         reply[replies].resp = NULL;
  437.         break;
  438.       default:
  439.         /* Must be an error of some sort... */
  440.         free (reply);
  441.         return PAM_CONV_ERR;
  442.     }
  443.   }
  444.   if (reply) *resp = reply;
  445.   return PAM_SUCCESS;
  446. }
  447. static struct pam_conv PAM_conversation = {
  448.     &PAM_conv,
  449.     NULL
  450. };
  451.  
  452.  
  453. static BOOL pam_auth(char *this_user,char *password)
  454. {
  455.   pam_handle_t *pamh;
  456.   int pam_error;
  457.  
  458.   /* Now use PAM to do authentication.  For now, we won't worry about
  459.    * session logging, only authentication.  Bail out if there are any
  460.    * errors.  Since this is a limited protocol, and an even more limited
  461.    * function within a server speaking this protocol, we can't be as
  462.    * verbose as would otherwise make sense.
  463.    * Query: should we be using PAM_SILENT to shut PAM up?
  464.    */
  465.   #define PAM_BAIL if (pam_error != PAM_SUCCESS) { \
  466.      pam_end(pamh, 0); return False; \
  467.    }
  468.   PAM_password = password;
  469.   PAM_username = this_user;
  470.   pam_error = pam_start("samba", this_user, &PAM_conversation, &pamh);
  471.   PAM_BAIL;
  472. /* Setting PAM_SILENT stops generation of error messages to syslog
  473.  * to enable debugging on Red Hat Linux set:
  474.  * /etc/pam.d/samba:
  475.  *    auth required /lib/security/pam_pwdb.so nullok shadow audit
  476.  * _OR_ change PAM_SILENT to 0 to force detailed reporting (logging)
  477.  */
  478.   pam_error = pam_authenticate(pamh, PAM_SILENT);
  479.   PAM_BAIL;
  480.   /* It is not clear to me that account management is the right thing
  481.    * to do, but it is not clear that it isn't, either.  This can be
  482.    * removed if no account management should be done.  Alternately,
  483.    * put a pam_allow.so entry in /etc/pam.conf for account handling. */
  484.   pam_error = pam_acct_mgmt(pamh, PAM_SILENT);
  485.   PAM_BAIL;
  486.   pam_end(pamh, PAM_SUCCESS);
  487.   /* If this point is reached, the user has been authenticated. */
  488.   return(True);
  489. }
  490. #endif
  491.  
  492.  
  493. #ifdef AFS_AUTH
  494. /*******************************************************************
  495. check on AFS authentication
  496. ********************************************************************/
  497. static BOOL afs_auth(char *this_user,char *password)
  498. {
  499.   long password_expires = 0;
  500.   char *reason;
  501.     
  502.   /* For versions of AFS prior to 3.3, this routine has few arguments, */
  503.   /* but since I can't find the old documentation... :-)               */
  504.   setpag();
  505.   if (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION+KA_USERAUTH_DOSETPAG,
  506.                  this_user,
  507.                  (char *) 0, /* instance */
  508.                  (char *) 0, /* cell */
  509.                  password,
  510.                  0,          /* lifetime, default */
  511.                  &password_expires, /*days 'til it expires */
  512.                  0,          /* spare 2 */
  513.                  &reason) == 0)
  514.     return(True);
  515.   return(False);
  516. }
  517. #endif
  518.  
  519.  
  520. #ifdef DFS_AUTH
  521.  
  522. sec_login_handle_t my_dce_sec_context;
  523. int dcelogin_atmost_once = 0;
  524.  
  525. /*******************************************************************
  526. check on a DCE/DFS authentication
  527. ********************************************************************/
  528. static BOOL dfs_auth(char *this_user,char *password)
  529. {
  530.   error_status_t err;
  531.   int err2;
  532.   int prterr;
  533.   boolean32 password_reset;
  534.   sec_passwd_rec_t my_dce_password;
  535.   sec_login_auth_src_t auth_src = sec_login_auth_src_network;
  536.   unsigned char dce_errstr[dce_c_error_string_len];
  537.  
  538.   /*
  539.    * We only go for a DCE login context if the given password
  540.    * matches that stored in the local password file.. 
  541.    * Assumes local passwd file is kept in sync w/ DCE RGY!
  542.    */
  543.  
  544.   /* Fix for original (broken) code from Brett Wooldridge <brettw@austin.ibm.com> */
  545.   if (dcelogin_atmost_once)
  546.     return (False);
  547.   /* This can be ifdefed as the DCE check below is stricter... */
  548. #ifndef NO_CRYPT
  549.   if ( strcmp((char *)crypt(password,this_salt),this_crypted) )
  550.     return (False);
  551. #endif
  552.  
  553.   if (sec_login_setup_identity(
  554.                    (unsigned char *)this_user,
  555.                    sec_login_no_flags,
  556.                    &my_dce_sec_context,
  557.                    &err) == 0)
  558.     {
  559.       dce_error_inq_text(err, dce_errstr, &err2);
  560.       DEBUG(0,("DCE Setup Identity for %s failed: %s\n",
  561.            this_user,dce_errstr));
  562.       return(False);
  563.     }
  564.  
  565.   my_dce_password.version_number = sec_passwd_c_version_none;
  566.   my_dce_password.pepper = NULL; 
  567.   my_dce_password.key.key_type = sec_passwd_plain;
  568.   my_dce_password.key.tagged_union.plain  = (idl_char *)password;
  569.   
  570.   if (sec_login_valid_and_cert_ident(my_dce_sec_context,
  571.                      &my_dce_password,
  572.                      &password_reset,
  573.                      &auth_src,
  574.                      &err) == 0 )
  575.     { 
  576.       dce_error_inq_text(err, dce_errstr, &err2);
  577.       DEBUG(0,("DCE Identity Validation failed for principal %s: %s\n",
  578.            this_user,dce_errstr));
  579.       
  580.       return(False);
  581.     }
  582.  
  583.   sec_login_set_context(my_dce_sec_context, &err);
  584.   if (err != error_status_ok )
  585.     {  
  586.       dce_error_inq_text(err, dce_errstr, &err2);
  587.       DEBUG(0,("DCE login failed for principal %s, cant set context: %s\n",
  588.            this_user,dce_errstr));
  589.       sec_login_purge_context(my_dce_sec_context, &err);
  590.       return(False);
  591.     }
  592.   else
  593.     {
  594.       DEBUG(0,("DCE login succeeded for principal %s on pid %d\n",
  595.            this_user, getpid()));
  596.     }
  597.  
  598.   dcelogin_atmost_once = 1;
  599.   return (True);
  600. }
  601.  
  602. void dfs_unlogin(void)
  603. {
  604.   error_status_t err;
  605.   int err2;
  606.   unsigned char dce_errstr[dce_c_error_string_len];
  607.  
  608.   sec_login_purge_context(my_dce_sec_context, &err);
  609.   if (err != error_status_ok )
  610.     {  
  611.       dce_error_inq_text(err, dce_errstr, &err2);
  612.       DEBUG(0,("DCE purge login context failed for server instance %d: %s\n",
  613.            getpid(), dce_errstr));
  614.     }
  615. }
  616.  
  617. #endif
  618.  
  619. #ifdef KRB5_AUTH
  620. /*******************************************************************
  621. check on Kerberos authentication
  622. ********************************************************************/
  623. static BOOL krb5_auth(char *this_user,char *password)
  624. {
  625.     krb5_data tgtname = {
  626.         0,
  627.         KRB5_TGS_NAME_SIZE,
  628.          KRB5_TGS_NAME
  629.      };
  630.     krb5_context kcontext;
  631.     krb5_principal kprinc;
  632.     krb5_principal server;
  633.     krb5_creds kcreds;
  634.     int options = 0;
  635.     krb5_address **addrs = (krb5_address **)0;
  636.     krb5_preauthtype *preauth = NULL;
  637.     krb5_keytab keytab = NULL;
  638.     krb5_timestamp now;
  639.     krb5_ccache ccache = NULL;
  640.     int retval;
  641.     char *name;
  642.  
  643.     if ( retval=krb5_init_context(&kcontext))
  644.     {
  645.         return(False);
  646.     }
  647.  
  648.     if ( retval = krb5_timeofday(kcontext, &now) )
  649.     {
  650.         return(False);
  651.     }
  652.  
  653.     if ( retval = krb5_cc_default(kcontext, &ccache) )
  654.     {
  655.         return(False);
  656.     }
  657.     
  658.     if ( retval = krb5_parse_name(kcontext, this_user, &kprinc) )
  659.     {
  660.         return(False);
  661.     }
  662.  
  663.     memset((char *)&kcreds, 0, sizeof(kcreds));
  664.  
  665.     kcreds.client = kprinc;
  666.     
  667.     if ((retval = krb5_build_principal_ext(kcontext, &server,
  668.         krb5_princ_realm(kcontext, kprinc)->length,
  669.         krb5_princ_realm(kcontext, kprinc)->data,
  670.         tgtname.length,
  671.         tgtname.data,
  672.         krb5_princ_realm(kcontext, kprinc)->length,
  673.         krb5_princ_realm(kcontext, kprinc)->data,
  674.         0)))
  675.     {
  676.          return(False);
  677.     }
  678.  
  679.     kcreds.server = server;
  680.  
  681.     retval = krb5_get_in_tkt_with_password(kcontext,
  682.         options,
  683.         addrs,
  684.         NULL,
  685.         preauth,
  686.         password,
  687.         0,
  688.         &kcreds,
  689.         0);
  690.  
  691.     if ( retval )
  692.     {
  693.         return(False);
  694.     }
  695.  
  696.     return(True);
  697. }
  698. #endif /* KRB5_AUTH */
  699.  
  700. #ifdef KRB4_AUTH
  701. /*******************************************************************
  702. check on Kerberos authentication
  703. ********************************************************************/
  704. static BOOL krb4_auth(char *this_user,char *password)
  705. {
  706.   char realm[REALM_SZ];
  707.   char tkfile[MAXPATHLEN];
  708.   
  709.   if (krb_get_lrealm(realm, 1) != KSUCCESS)
  710.     (void) strncpy(realm, KRB_REALM, sizeof (realm));
  711.   
  712.   (void) slprintf(tkfile, sizeof(tkfile)-1, "/tmp/samba_tkt_%d", getpid());
  713.   
  714.   krb_set_tkt_string(tkfile);
  715.   if (krb_verify_user(this_user, "", realm,
  716.                      password, 0,
  717.                      "rmcd") == KSUCCESS) {
  718.     unlink(tkfile);
  719.     return 1;
  720.   }
  721.   unlink(tkfile);
  722.   return 0;
  723. }
  724. #endif /* KRB4_AUTH */
  725.  
  726. #ifdef LINUX_BIGCRYPT
  727. /****************************************************************************
  728. an enhanced crypt for Linux to handle password longer than 8 characters
  729. ****************************************************************************/
  730. static int linux_bigcrypt(char *password,char *salt1, char *crypted)
  731. {
  732. #define LINUX_PASSWORD_SEG_CHARS 8
  733.   char salt[3];
  734.   int i;
  735.   
  736.   StrnCpy(salt,salt1,2);
  737.   crypted +=2;
  738.   
  739.   for ( i=strlen(password); i > 0; i -= LINUX_PASSWORD_SEG_CHARS) {
  740.     char * p = crypt(password,salt) + 2;
  741.     if (strncmp(p, crypted, LINUX_PASSWORD_SEG_CHARS) != 0)
  742.       return(0);
  743.     password += LINUX_PASSWORD_SEG_CHARS;
  744.     crypted  += strlen(p);
  745.   }
  746.   
  747.   return(1);
  748. }
  749. #endif
  750.  
  751.  
  752. /****************************************************************************
  753. apply a function to upper/lower case combinations
  754. of a string and return true if one of them returns true.
  755. try all combinations with N uppercase letters.
  756. offset is the first char to try and change (start with 0)
  757. it assumes the string starts lowercased
  758. ****************************************************************************/
  759. static BOOL string_combinations2(char *s,int offset,BOOL (*fn)(char *),int N)
  760. {
  761.   int len = strlen(s);
  762.   int i;
  763.  
  764. #ifdef PASSWORD_LENGTH
  765.   len = MIN(len,PASSWORD_LENGTH);
  766. #endif
  767.  
  768.   if (N <= 0 || offset >= len)
  769.     return(fn(s));
  770.  
  771.   for (i=offset;i<(len-(N-1));i++)
  772.     {      
  773.       char c = s[i];
  774.       if (!islower(c)) continue;
  775.       s[i] = toupper(c);
  776.       if (string_combinations2(s,i+1,fn,N-1))
  777.     return(True);
  778.       s[i] = c;
  779.     }
  780.   return(False);
  781. }
  782.  
  783. /****************************************************************************
  784. apply a function to upper/lower case combinations
  785. of a string and return true if one of them returns true.
  786. try all combinations with up to N uppercase letters.
  787. offset is the first char to try and change (start with 0)
  788. it assumes the string starts lowercased
  789. ****************************************************************************/
  790. static BOOL string_combinations(char *s,BOOL (*fn)(char *),int N)
  791. {
  792.   int n;
  793.   for (n=1;n<=N;n++)
  794.     if (string_combinations2(s,0,fn,n)) return(True);
  795.   return(False);
  796. }
  797.  
  798.  
  799.  
  800. /****************************************************************************
  801. core of password checking routine
  802. ****************************************************************************/
  803. BOOL password_check(char *password)
  804. {
  805.  
  806. #ifdef USE_PAM
  807. /* This falls through if the password check fails
  808.     - if NO_CRYPT is defined this causes an error msg
  809.         saying Warning - no crypt available
  810.     - if NO_CRYPT is NOT defined this is a potential security hole
  811.         as it may authenticate via the crypt call when PAM
  812.         settings say it should fail.
  813.   if (pam_auth(this_user,password)) return(True);
  814. Hence we make a direct return to avoid a second chance!!!
  815. */
  816.   return (pam_auth(this_user,password));
  817. #endif
  818.  
  819. #ifdef AFS_AUTH
  820.   if (afs_auth(this_user,password)) return(True);
  821. #endif
  822.  
  823. #ifdef DFS_AUTH
  824.   if (dfs_auth(this_user,password)) return(True);
  825. #endif 
  826.  
  827. #ifdef KRB5_AUTH
  828.   if (krb5_auth(this_user,password)) return(True);
  829. #endif
  830.  
  831. #ifdef KRB4_AUTH
  832.   if (krb4_auth(this_user,password)) return(True);
  833. #endif
  834.  
  835. #ifdef PWDAUTH
  836.   if (pwdauth(this_user,password) == 0)
  837.     return(True);
  838. #endif
  839.  
  840. #ifdef OSF1_ENH_SEC
  841.   {
  842.     BOOL ret = (strcmp(osf1_bigcrypt(password,this_salt),this_crypted) == 0);
  843.     if(!ret) {
  844.       DEBUG(2,("password_check: OSF1_ENH_SEC failed. Trying normal crypt.\n"));
  845.       ret = (strcmp((char *)crypt(password,this_salt),this_crypted) == 0);
  846.     }
  847.     return ret;
  848.   }
  849. #endif
  850.  
  851. #ifdef ULTRIX_AUTH
  852.   return (strcmp((char *)crypt16(password, this_salt ),this_crypted) == 0);
  853. #endif
  854.  
  855. #ifdef LINUX_BIGCRYPT
  856.   return(linux_bigcrypt(password,this_salt,this_crypted));
  857. #endif
  858.  
  859. #ifdef HPUX_10_TRUSTED
  860.   return(strcmp(bigcrypt(password,this_salt),this_crypted) == 0);
  861. #endif
  862.  
  863. #ifdef NO_CRYPT
  864.   DEBUG(1,("Warning - no crypt available\n"));
  865.   return(False);
  866. #else
  867.   return(strcmp((char *)crypt(password,this_salt),this_crypted) == 0);
  868. #endif
  869. }
  870.  
  871. /****************************************************************************
  872. core of smb password checking routine.
  873. ****************************************************************************/
  874. BOOL smb_password_check(char *password, unsigned char *part_passwd, unsigned char *c8)
  875. {
  876.   /* Finish the encryption of part_passwd. */
  877.   unsigned char p21[21];
  878.   unsigned char p24[24];
  879.  
  880.   if (part_passwd == NULL)
  881.     DEBUG(10,("No password set - allowing access\n"));
  882.   /* No password set - always true ! */
  883.   if (part_passwd == NULL)
  884.     return 1;
  885.  
  886.   memset(p21,'\0',21);
  887.   memcpy(p21,part_passwd,16);
  888.   E_P24(p21, c8, p24);
  889. #if DEBUG_PASSWORD
  890.   {
  891.     int i;
  892.     DEBUG(100,("Part password (P16) was |"));
  893.     for(i = 0; i < 16; i++)
  894.       DEBUG(100,("%X ", (unsigned char)part_passwd[i]));
  895.     DEBUG(100,("|\n"));
  896.     DEBUG(100,("Password from client was |"));
  897.     for(i = 0; i < 24; i++)
  898.       DEBUG(100,("%X ", (unsigned char)password[i]));
  899.     DEBUG(100,("|\n"));
  900.     DEBUG(100,("Given challenge was |"));
  901.     for(i = 0; i < 8; i++)
  902.       DEBUG(100,("%X ", (unsigned char)c8[i]));
  903.     DEBUG(100,("|\n"));
  904.     DEBUG(100,("Value from encryption was |"));
  905.     for(i = 0; i < 24; i++)
  906.       DEBUG(100,("%X ", (unsigned char)p24[i]));
  907.     DEBUG(100,("|\n"));
  908.   }
  909. #endif
  910.   return (memcmp(p24, password, 24) == 0);
  911. }
  912.  
  913. /****************************************************************************
  914. check if a username/password is OK
  915. ****************************************************************************/
  916. BOOL password_ok(char *user,char *password, int pwlen, struct passwd *pwd)
  917. {
  918.   pstring pass2;
  919.   int level = lp_passwordlevel();
  920.   struct passwd *pass;
  921.   char challenge[8];
  922.   BOOL update_encrypted = lp_update_encrypted();
  923.   struct smb_passwd *smb_pass;
  924.   BOOL challenge_done = False;
  925.  
  926.   if (password) password[pwlen] = 0;
  927.  
  928.   if (pwlen == 24)
  929.     challenge_done = last_challenge(challenge);
  930.  
  931. #if DEBUG_PASSWORD
  932.   if (challenge_done)
  933.     {
  934.       int i;      
  935.       DEBUG(100,("checking user=[%s] pass=[",user));
  936.       for( i = 0; i < 24; i++)
  937.     DEBUG(100,("%0x ", (unsigned char)password[i]));
  938.       DEBUG(100,("]\n"));
  939.     } else {
  940.         DEBUG(100,("checking user=[%s] pass=[%s]\n",user,password));
  941.     }
  942. #endif
  943.  
  944.   if (!password)
  945.     return(False);
  946.  
  947.   if (((!*password) || (!pwlen)) && !lp_null_passwords())
  948.     return(False);
  949.  
  950.   if (pwd && !user) 
  951.     {
  952.       pass = (struct passwd *) pwd;
  953.       user = pass->pw_name;
  954.     } 
  955.   else 
  956.     pass = Get_Pwnam(user,True);
  957.  
  958.   DEBUG(4,("SMB Password - pwlen = %d, challenge_done = %d\n", pwlen, challenge_done));
  959.  
  960.   if ((pwlen == 24) && challenge_done)
  961.   {
  962.     DEBUG(4,("Checking SMB password for user %s (l=24)\n",user));
  963.  
  964.     if (!pass) 
  965.     {
  966.       DEBUG(3,("Couldn't find user %s\n",user));
  967.       return(False);
  968.     }
  969.  
  970.     /* non-null username indicates search by username not smb userid */
  971.     smb_pass = get_smbpwd_entry(user, 0);
  972.     if (!smb_pass)
  973.     {
  974.       DEBUG(3,("Couldn't find user %s in smb_passwd file.\n", user));
  975.       return(False);
  976.     }
  977.  
  978.     if(smb_pass->acct_ctrl & ACB_DISABLED)
  979.     {
  980.       DEBUG(3,("password_ok: account for user %s was disabled.\n", user));
  981.           return(False);
  982.     }
  983.  
  984.       /* Ensure the uid's match */
  985.     if (smb_pass->smb_userid != pass->pw_uid)
  986.     {
  987.       DEBUG(3,("Error : UNIX and SMB uids in password files do not match !\n"));
  988.       return(False);
  989.     }
  990.  
  991.     if (Protocol >= PROTOCOL_NT1)
  992.     {
  993.       /* We have the NT MD4 hash challenge available - see if we can
  994.          use it (ie. does it exist in the smbpasswd file).
  995.        */
  996.       if (smb_pass->smb_nt_passwd != NULL)
  997.       {
  998.         DEBUG(4,("Checking NT MD4 password\n"));
  999.         if (smb_password_check(password, 
  1000.                                smb_pass->smb_nt_passwd, 
  1001.                                (unsigned char *)challenge))
  1002.         {
  1003.           update_protected_database(user,True);
  1004.           return(True);
  1005.         }
  1006.         DEBUG(4,("NT MD4 password check failed\n"));
  1007.       }
  1008.     }
  1009.  
  1010.     /* Try against the lanman password */
  1011.     if((smb_pass->smb_passwd == NULL) && (smb_pass->acct_ctrl & ACB_PWNOTREQ ))
  1012.     {
  1013.       /* No password. */
  1014.       DEBUG(1,("password_ok: User %s has NO PASSWORD !\n", user));
  1015.       update_protected_database(user,True);
  1016.       return(True);
  1017.     }
  1018.  
  1019.     if ((smb_pass->smb_passwd != NULL) && 
  1020.         smb_password_check(password, smb_pass->smb_passwd,
  1021.                            (unsigned char *)challenge))
  1022.     {
  1023.       update_protected_database(user,True);
  1024.       return(True);
  1025.     }
  1026.  
  1027.     DEBUG(3,("Error smb_password_check failed\n"));
  1028.   }
  1029.  
  1030.   DEBUG(4,("Checking password for user %s (l=%d)\n",user,pwlen));
  1031.  
  1032.   if (!pass) 
  1033.     {
  1034.       DEBUG(3,("Couldn't find user %s\n",user));
  1035.       return(False);
  1036.     }
  1037.  
  1038. #ifdef SHADOW_PWD
  1039.   {
  1040.     struct spwd *spass;
  1041.  
  1042.     /* many shadow systems require you to be root to get the password,
  1043.        in most cases this should already be the case when this
  1044.        function is called, except perhaps for IPC password changing
  1045.        requests */
  1046.  
  1047.     spass = getspnam(pass->pw_name);
  1048.     if (spass && spass->sp_pwdp)
  1049.       pass->pw_passwd = spass->sp_pwdp;
  1050.   }
  1051. #elif defined(IA_UINFO)
  1052.   {
  1053.       /* Need to get password with SVR4.2's ia_ functions instead of
  1054.          get{sp,pw}ent functions. Required by UnixWare 2.x, tested on 
  1055.          version 2.1. (tangent@cyberport.com) */
  1056.       uinfo_t uinfo;
  1057.       if (ia_openinfo(pass->pw_name, &uinfo) != -1)
  1058.         ia_get_logpwd(uinfo, &(pass->pw_passwd));
  1059.   }
  1060. #endif
  1061.  
  1062. #ifdef SecureWare
  1063.   {
  1064.     struct pr_passwd *pr_pw = getprpwnam(pass->pw_name);
  1065.     if (pr_pw && pr_pw->ufld.fd_encrypt)
  1066.       pass->pw_passwd = pr_pw->ufld.fd_encrypt;
  1067.   }
  1068. #endif
  1069.  
  1070. #ifdef HPUX_10_TRUSTED
  1071.   {
  1072.     struct pr_passwd *pr_pw = getprpwnam(pass->pw_name);
  1073.     if (pr_pw && pr_pw->ufld.fd_encrypt)
  1074.       pass->pw_passwd = pr_pw->ufld.fd_encrypt;
  1075.   }
  1076. #endif
  1077.  
  1078. #ifdef OSF1_ENH_SEC
  1079.   {
  1080.     struct pr_passwd *mypasswd;
  1081.     DEBUG(5,("Checking password for user %s in OSF1_ENH_SEC\n",user));
  1082.     mypasswd = getprpwnam (user);
  1083.     if ( mypasswd )
  1084.       { 
  1085.       pstrcpy(pass->pw_name,mypasswd->ufld.fd_name);
  1086.       pstrcpy(pass->pw_passwd,mypasswd->ufld.fd_encrypt);
  1087.       }
  1088.     else
  1089.       {
  1090.     DEBUG(5,("No entry for user %s in protected database !\n",user));
  1091.     return(False);
  1092.       }
  1093.   }
  1094. #endif
  1095.  
  1096. #ifdef ULTRIX_AUTH
  1097.   {
  1098.     AUTHORIZATION *ap = getauthuid( pass->pw_uid );
  1099.     if (ap)
  1100.       {
  1101.     pstrcpy( pass->pw_passwd, ap->a_password );
  1102.     endauthent();
  1103.       }
  1104.   }
  1105. #endif
  1106.  
  1107.   /* extract relevant info */
  1108.   fstrcpy(this_user,pass->pw_name);  
  1109.   fstrcpy(this_salt,pass->pw_passwd);
  1110. #ifdef HPUX
  1111.   /* The crypt on HPUX won't work with more than 2 salt characters. */
  1112.   this_salt[2] = 0;
  1113. #endif /* HPUX */
  1114.   fstrcpy(this_crypted,pass->pw_passwd);
  1115.  
  1116.   if (!*this_crypted) {
  1117.     if (!lp_null_passwords()) {
  1118.       DEBUG(2,("Disallowing access to %s due to null password\n",this_user));
  1119.       return(False);
  1120.     }
  1121. #ifndef PWDAUTH
  1122.     if (!*password) {
  1123.       DEBUG(3,("Allowing access to %s with null password\n",this_user));
  1124.       return(True);
  1125.     }
  1126. #endif    
  1127.   }
  1128.  
  1129.   /* try it as it came to us */
  1130.   if (password_check(password))
  1131.     {
  1132.       update_protected_database(user,True);
  1133.       if (pass && update_encrypted)
  1134.         update_smbpassword_file(pass,password);
  1135.       return(True);
  1136.     }
  1137.  
  1138.   /* if the password was given to us with mixed case then we don't
  1139.      need to proceed as we know it hasn't been case modified by the
  1140.      client */
  1141.   if (strhasupper(password) && strhaslower(password))
  1142.     return(False);
  1143.  
  1144.   /* make a copy of it */
  1145.   StrnCpy(pass2,password,sizeof(pstring)-1);
  1146.   
  1147.   /* try all lowercase */
  1148.   strlower(password);
  1149.   if (password_check(password))
  1150.     {
  1151.       update_protected_database(user,True);
  1152.       if (pass && update_encrypted)
  1153.         update_smbpassword_file(pass,password);
  1154.       return(True);
  1155.     }
  1156.  
  1157.   /* give up? */
  1158.   if (level < 1)
  1159.     {
  1160.       update_protected_database(user,False);
  1161.  
  1162.       /* restore it */
  1163.       pstrcpy(password,pass2);
  1164.  
  1165.       return(False);
  1166.     }
  1167.  
  1168.   /* last chance - all combinations of up to level chars upper! */
  1169.   strlower(password);
  1170.  
  1171.   if (string_combinations(password,password_check,level))
  1172.     {
  1173.       update_protected_database(user,True);
  1174.       if (pass && update_encrypted)
  1175.         update_smbpassword_file(pass,password);
  1176.       return(True);
  1177.     }
  1178.  
  1179.   update_protected_database(user,False);
  1180.   
  1181.   /* restore it */
  1182.   pstrcpy(password,pass2);
  1183.   
  1184.   return(False);
  1185. }
  1186.  
  1187.  
  1188.  
  1189. /****************************************************************************
  1190. check if a username is valid
  1191. ****************************************************************************/
  1192. BOOL user_ok(char *user,int snum)
  1193. {
  1194.   pstring valid, invalid;
  1195.   BOOL ret;
  1196.  
  1197.   StrnCpy(valid, lp_valid_users(snum), sizeof(pstring));
  1198.   StrnCpy(invalid, lp_invalid_users(snum), sizeof(pstring));
  1199.  
  1200.   string_sub(valid,"%S",lp_servicename(snum));
  1201.   string_sub(invalid,"%S",lp_servicename(snum));
  1202.  
  1203.   ret = !user_in_list(user,invalid);
  1204.  
  1205.   if (ret && valid && *valid)
  1206.     ret = user_in_list(user,valid);
  1207.  
  1208.   if (ret && lp_onlyuser(snum)) {
  1209.     char *user_list = lp_username(snum);
  1210.     string_sub(user_list,"%S",lp_servicename(snum));
  1211.     ret = user_in_list(user,user_list);
  1212.   }
  1213.  
  1214.   return(ret);
  1215. }
  1216.  
  1217.  
  1218.  
  1219.  
  1220. /****************************************************************************
  1221. validate a group username entry. Return the username or NULL
  1222. ****************************************************************************/
  1223. static char *validate_group(char *group,char *password,int pwlen,int snum)
  1224. {
  1225. #ifdef NETGROUP
  1226.   {
  1227.     char *host, *user, *domain;
  1228.     setnetgrent(group);
  1229.     while (getnetgrent(&host, &user, &domain)) {
  1230.       if (user) {
  1231.     if (user_ok(user, snum) && 
  1232.         password_ok(user,password,pwlen,NULL)) {
  1233.       endnetgrent();
  1234.       return(user);
  1235.     }
  1236.       }
  1237.     }
  1238.     endnetgrent();
  1239.   }
  1240. #endif
  1241.   
  1242. #if HAVE_GETGRNAM 
  1243.   {
  1244.     struct group *gptr = (struct group *)getgrnam(group);
  1245.     char **member;
  1246.     if (gptr)
  1247.       {
  1248.     member = gptr->gr_mem;
  1249.     while (member && *member)
  1250.       {
  1251.         static fstring name;
  1252.         fstrcpy(name,*member);
  1253.         if (user_ok(name,snum) &&
  1254.         password_ok(name,password,pwlen,NULL))
  1255.           return(&name[0]);
  1256.         member++;
  1257.       }
  1258. #ifdef GROUP_CHECK_PWENT
  1259.     {
  1260.       struct passwd *pwd;
  1261.       static fstring tm;
  1262.       
  1263.       setpwent ();
  1264.       while (pwd = getpwent ()) {
  1265.         if (*(pwd->pw_passwd) && pwd->pw_gid == gptr->gr_gid) {
  1266.           /* This Entry have PASSWORD and same GID then check pwd */
  1267.           if (password_ok(NULL, password, pwlen, pwd)) {
  1268.         fstrcpy(tm, pwd->pw_name);
  1269.         endpwent ();
  1270.         return tm;
  1271.           }
  1272.         }
  1273.       }
  1274.       endpwent ();
  1275.     }
  1276. #endif /* GROUP_CHECK_PWENT */
  1277.       }
  1278.   }      
  1279. #endif
  1280.   return(NULL);
  1281. }
  1282.  
  1283.  
  1284.  
  1285. /****************************************************************************
  1286. check for authority to login to a service with a given username/password
  1287. ****************************************************************************/
  1288. BOOL authorise_login(int snum,char *user,char *password, int pwlen, 
  1289.              BOOL *guest,BOOL *force,uint16 vuid)
  1290. {
  1291.   BOOL ok = False;
  1292.   
  1293.   *guest = False;
  1294.   
  1295. #if DEBUG_PASSWORD
  1296.   DEBUG(100,("checking authorisation on user=%s pass=%s\n",user,password));
  1297. #endif
  1298.  
  1299.   /* there are several possibilities:
  1300.      1) login as the given user with given password
  1301.      2) login as a previously registered username with the given password
  1302.      3) login as a session list username with the given password
  1303.      4) login as a previously validated user/password pair
  1304.      5) login as the "user =" user with given password
  1305.      6) login as the "user =" user with no password (guest connection)
  1306.      7) login as guest user with no password
  1307.  
  1308.      if the service is guest_only then steps 1 to 5 are skipped
  1309.   */
  1310.  
  1311.   if (GUEST_ONLY(snum)) *force = True;
  1312.  
  1313.   if (!(GUEST_ONLY(snum) && GUEST_OK(snum)))
  1314.     {
  1315.  
  1316.       user_struct *vuser = get_valid_user_struct(vuid);
  1317.  
  1318.       /* check the given username and password */
  1319.       if (!ok && (*user) && user_ok(user,snum)) {
  1320.     ok = password_ok(user,password, pwlen, NULL);
  1321.     if (ok) DEBUG(3,("ACCEPTED: given username password ok\n"));
  1322.       }
  1323.  
  1324.       /* check for a previously registered guest username */
  1325.       if (!ok && (vuser != 0) && vuser->guest) {      
  1326.     if (user_ok(vuser->name,snum) &&
  1327.         password_ok(vuser->name, password, pwlen, NULL)) {
  1328.       pstrcpy(user, vuser->name);
  1329.       vuser->guest = False;
  1330.       DEBUG(3,("ACCEPTED: given password with registered user %s\n", user));
  1331.       ok = True;
  1332.     }
  1333.       }
  1334.  
  1335.  
  1336.       /* now check the list of session users */
  1337.       if (!ok)
  1338.     {
  1339.       char *auser;
  1340.       char *user_list = strdup(session_users);
  1341.       if (!user_list) return(False);
  1342.  
  1343.       for (auser=strtok(user_list,LIST_SEP); 
  1344.            !ok && auser; 
  1345.            auser = strtok(NULL,LIST_SEP))
  1346.         {
  1347.           fstring user2;
  1348.           fstrcpy(user2,auser);
  1349.           if (!user_ok(user2,snum)) continue;
  1350.           
  1351.           if (password_ok(user2,password, pwlen, NULL)) {
  1352.         ok = True;
  1353.         pstrcpy(user,user2);
  1354.         DEBUG(3,("ACCEPTED: session list username and given password ok\n"));
  1355.           }
  1356.         }
  1357.       free(user_list);
  1358.     }
  1359.  
  1360.       /* check for a previously validated username/password pair */
  1361.       if (!ok && (!lp_revalidate(snum) || lp_security() > SEC_SHARE) &&
  1362.       (vuser != 0) && !vuser->guest &&
  1363.       user_ok(vuser->name,snum)) {
  1364.     pstrcpy(user,vuser->name);
  1365.     *guest = False;
  1366.     DEBUG(3,("ACCEPTED: validated uid ok as non-guest\n"));
  1367.     ok = True;
  1368.       }
  1369.  
  1370.       /* check for a rhosts entry */
  1371.       if (!ok && user_ok(user,snum) && check_hosts_equiv(user)) {
  1372.     ok = True;
  1373.     DEBUG(3,("ACCEPTED: hosts equiv or rhosts entry\n"));
  1374.       }
  1375.  
  1376.       /* check the user= fields and the given password */
  1377.       if (!ok && lp_username(snum)) {
  1378.     char *auser;
  1379.     pstring user_list;
  1380.     StrnCpy(user_list,lp_username(snum),sizeof(pstring));
  1381.  
  1382.     string_sub(user_list,"%S",lp_servicename(snum));
  1383.       
  1384.     for (auser=strtok(user_list,LIST_SEP);
  1385.          auser && !ok;
  1386.          auser = strtok(NULL,LIST_SEP))
  1387.       {
  1388.         if (*auser == '@')
  1389.           {
  1390.         auser = validate_group(auser+1,password,pwlen,snum);
  1391.         if (auser)
  1392.           {
  1393.             ok = True;
  1394.             pstrcpy(user,auser);
  1395.             DEBUG(3,("ACCEPTED: group username and given password ok\n"));
  1396.           }
  1397.           }
  1398.         else
  1399.           {
  1400.         fstring user2;
  1401.         fstrcpy(user2,auser);
  1402.         if (user_ok(user2,snum) && 
  1403.             password_ok(user2,password,pwlen,NULL))
  1404.           {
  1405.             ok = True;
  1406.             pstrcpy(user,user2);
  1407.             DEBUG(3,("ACCEPTED: user list username and given password ok\n"));
  1408.           }
  1409.           }
  1410.       }
  1411.       }      
  1412.     } /* not guest only */
  1413.  
  1414.   /* check for a normal guest connection */
  1415.   if (!ok && GUEST_OK(snum))
  1416.     {
  1417.       fstring guestname;
  1418.       StrnCpy(guestname,lp_guestaccount(snum),sizeof(guestname)-1);
  1419.       if (Get_Pwnam(guestname,True))
  1420.     {
  1421.       pstrcpy(user,guestname);
  1422.       ok = True;
  1423.       DEBUG(3,("ACCEPTED: guest account and guest ok\n"));
  1424.     }
  1425.       else
  1426.     DEBUG(0,("Invalid guest account %s??\n",guestname));
  1427.       *guest = True;
  1428.       *force = True;
  1429.     }
  1430.  
  1431.   if (ok && !user_ok(user,snum))
  1432.     {
  1433.       DEBUG(0,("rejected invalid user %s\n",user));
  1434.       ok = False;
  1435.     }
  1436.  
  1437.   return(ok);
  1438. }
  1439.  
  1440.  
  1441. /****************************************************************************
  1442. read the a hosts.equiv or .rhosts file and check if it
  1443. allows this user from this machine
  1444. ****************************************************************************/
  1445. static BOOL check_user_equiv(char *user, char *remote, char *equiv_file)
  1446. {
  1447.   pstring buf;
  1448.   int plus_allowed = 1;
  1449.   char *file_host;
  1450.   char *file_user;
  1451.   FILE *fp = fopen(equiv_file, "r");
  1452.   DEBUG(5, ("check_user_equiv %s %s %s\n", user, remote, equiv_file));
  1453.   if (! fp) return False;
  1454.   while(fgets(buf, sizeof(buf), fp)) 
  1455.   {
  1456.     trim_string(buf," "," ");
  1457.  
  1458.     if (buf[0] != '#' && buf[0] != '\n') 
  1459.     {
  1460.       BOOL is_group = False;
  1461.       int plus = 1;
  1462.       char *bp = buf;
  1463.       if (strcmp(buf, "NO_PLUS\n") == 0)
  1464.       {
  1465.     DEBUG(6, ("check_user_equiv NO_PLUS\n"));
  1466.     plus_allowed = 0;
  1467.       }
  1468.       else {
  1469.     if (buf[0] == '+') 
  1470.     {
  1471.       bp++;
  1472.       if (*bp == '\n' && plus_allowed) 
  1473.       {
  1474.         /* a bare plus means everbody allowed */
  1475.         DEBUG(6, ("check_user_equiv everybody allowed\n"));
  1476.         fclose(fp);
  1477.         return True;
  1478.       }
  1479.     }
  1480.     else if (buf[0] == '-')
  1481.     {
  1482.       bp++;
  1483.       plus = 0;
  1484.     }
  1485.     if (*bp == '@') 
  1486.     {
  1487.       is_group = True;
  1488.       bp++;
  1489.     }
  1490.     file_host = strtok(bp, " \t\n");
  1491.     file_user = strtok(NULL, " \t\n");
  1492.     DEBUG(7, ("check_user_equiv %s %s\n", file_host ? file_host : "(null)", 
  1493.                  file_user ? file_user : "(null)" ));
  1494.     if (file_host && *file_host) 
  1495.     {
  1496.       BOOL host_ok = False;
  1497.  
  1498. #ifdef NETGROUP      
  1499.       if (is_group)
  1500.         {
  1501.           static char *mydomain = NULL;
  1502.           if (!mydomain)
  1503.         yp_get_default_domain(&mydomain);
  1504.           if (mydomain && innetgr(file_host,remote,user,mydomain))
  1505.         host_ok = True;
  1506.         }
  1507. #else
  1508.       if (is_group)
  1509.         {
  1510.           DEBUG(1,("Netgroups not configured - add -DNETGROUP and recompile\n"));
  1511.           continue;
  1512.         }
  1513. #endif
  1514.  
  1515.       /* is it this host */
  1516.       /* the fact that remote has come from a call of gethostbyaddr
  1517.        * means that it may have the fully qualified domain name
  1518.        * so we could look up the file version to get it into
  1519.        * a canonical form, but I would rather just type it
  1520.        * in full in the equiv file
  1521.        */
  1522.       if (!host_ok && !is_group && strequal(remote, file_host))
  1523.         host_ok = True;
  1524.  
  1525.       if (!host_ok)
  1526.         continue;
  1527.  
  1528.       /* is it this user */
  1529.       if (file_user == 0 || strequal(user, file_user)) 
  1530.         {
  1531.           fclose(fp);
  1532.           DEBUG(5, ("check_user_equiv matched %s%s %s\n",
  1533.             (plus ? "+" : "-"), file_host,
  1534.             (file_user ? file_user : "")));
  1535.           return (plus ? True : False);
  1536.         }
  1537.     }
  1538.       }
  1539.     }
  1540.   }
  1541.   fclose(fp);
  1542.   return False;
  1543. }
  1544.  
  1545.  
  1546. /****************************************************************************
  1547. check for a possible hosts equiv or rhosts entry for the user
  1548. ****************************************************************************/
  1549. BOOL check_hosts_equiv(char *user)
  1550. {
  1551.   char *fname = NULL;
  1552.   pstring rhostsfile;
  1553.   struct passwd *pass = Get_Pwnam(user,True);
  1554.  
  1555.   if (!pass) 
  1556.     return(False);
  1557.  
  1558.   fname = lp_hosts_equiv();
  1559.  
  1560.   /* note: don't allow hosts.equiv on root */
  1561.   if (fname && *fname && (pass->pw_uid != 0))
  1562.     {
  1563.       if (check_user_equiv(user,client_name(),fname))
  1564.     return(True);
  1565.     }
  1566.   
  1567.   if (lp_use_rhosts())
  1568.     {
  1569.       char *home = get_home_dir(user);
  1570.       if (home)
  1571.     {
  1572.       slprintf(rhostsfile, sizeof(rhostsfile)-1, "%s/.rhosts", home);
  1573.       if (check_user_equiv(user,client_name(),rhostsfile))
  1574.         return(True);
  1575.     }
  1576.     }
  1577.  
  1578.   return(False);
  1579. }
  1580.  
  1581.  
  1582. static struct cli_state cli;
  1583.  
  1584. /****************************************************************************
  1585. return the client state structure
  1586. ****************************************************************************/
  1587. struct cli_state *server_client(void)
  1588. {
  1589.     return &cli;
  1590. }
  1591.  
  1592. /****************************************************************************
  1593. support for server level security 
  1594. ****************************************************************************/
  1595. struct cli_state *server_cryptkey(void)
  1596. {
  1597.     fstring desthost;
  1598.     struct in_addr dest_ip;
  1599.     extern fstring local_machine;
  1600.     char *p;
  1601.  
  1602.     if (!cli_initialise(&cli))
  1603.         return NULL;
  1604.         
  1605.     for (p=strtok(lp_passwordserver(),LIST_SEP); p ; p = strtok(NULL,LIST_SEP)) {
  1606.         fstrcpy(desthost,p);
  1607.         standard_sub_basic(desthost);
  1608.         strupper(desthost);
  1609.  
  1610.                 if(!resolve_name( desthost, &dest_ip)) {
  1611.             DEBUG(1,("server_cryptkey: Can't resolve address for %s\n",p));
  1612.             continue;
  1613.         }
  1614.  
  1615.         if (ismyip(dest_ip)) {
  1616.             DEBUG(1,("Password server loop - disabling password server %s\n",p));
  1617.             continue;
  1618.         }
  1619.  
  1620.         if (cli_connect(&cli, desthost, &dest_ip)) {
  1621.             DEBUG(3,("connected to password server %s\n",p));
  1622.             break;
  1623.         }
  1624.     }
  1625.  
  1626.     if (!p) {
  1627.         DEBUG(1,("password server not available\n"));
  1628.         cli_shutdown(&cli);
  1629.         return NULL;
  1630.     }
  1631.  
  1632.     if (!cli_session_request(&cli, desthost, 0x20, local_machine)) {
  1633.         DEBUG(1,("%s rejected the session\n",desthost));
  1634.         cli_shutdown(&cli);
  1635.         return NULL;
  1636.     }
  1637.  
  1638.     DEBUG(3,("got session\n"));
  1639.  
  1640.     if (!cli_negprot(&cli)) {
  1641.         DEBUG(1,("%s rejected the negprot\n",desthost));
  1642.         cli_shutdown(&cli);
  1643.         return NULL;
  1644.     }
  1645.  
  1646.     if (cli.protocol < PROTOCOL_LANMAN2 ||
  1647.         !(cli.sec_mode & 1)) {
  1648.         DEBUG(1,("%s isn't in user level security mode\n",desthost));
  1649.         cli_shutdown(&cli);
  1650.         return NULL;
  1651.     }
  1652.  
  1653.     DEBUG(3,("password server OK\n"));
  1654.  
  1655.     return &cli;
  1656. }
  1657.  
  1658. /****************************************************************************
  1659. validate a password with the password server
  1660. ****************************************************************************/
  1661. BOOL server_validate(char *user, char *domain, 
  1662.              char *pass, int passlen,
  1663.              char *ntpass, int ntpasslen)
  1664. {
  1665.     extern fstring local_machine;
  1666.         static unsigned char badpass[24];
  1667.  
  1668.     if (!cli.initialised) {
  1669.         DEBUG(1,("password server %s is not connected\n", cli.desthost));
  1670.         return(False);
  1671.     }  
  1672.  
  1673.         if(badpass[0] == 0) {
  1674.           memset(badpass, 0x1f, sizeof(badpass));
  1675.         }
  1676.  
  1677.         if((passlen == sizeof(badpass)) && !memcmp(badpass, pass, passlen)) {
  1678.           /* Very unlikely, our random bad password is the same as the users
  1679.              password. */
  1680.           memset(badpass, badpass[0]+1, sizeof(badpass));
  1681.         }
  1682.  
  1683.         /*
  1684.          * Attempt a session setup with a totally incorrect password.
  1685.          * If this succeeds with the guest bit *NOT* set then the password
  1686.          * server is broken and is not correctly setting the guest bit. We
  1687.          * need to detect this as some versions of NT4.x are broken. JRA.
  1688.          */
  1689.  
  1690.         if (cli_session_setup(&cli, user, (char *)badpass, sizeof(badpass), 
  1691.                               (char *)badpass, sizeof(badpass), domain)) {
  1692.           if ((SVAL(cli.inbuf,smb_vwv2) & 1) == 0) {
  1693.             DEBUG(0,("server_validate: password server %s allows users as non-guest \
  1694. with a bad password.\n", cli.desthost));
  1695.             DEBUG(0,("server_validate: This is broken (and insecure) behaviour. Please do not \
  1696. use this machine as the password server.\n"));
  1697.             cli_ulogoff(&cli);
  1698.             return False;
  1699.           }
  1700.           cli_ulogoff(&cli);
  1701.         }
  1702.  
  1703.         /*
  1704.          * Now we know the password server will correctly set the guest bit, or is
  1705.          * not guest enabled, we can try with the real password.
  1706.          */
  1707.  
  1708.     if (!cli_session_setup(&cli, user, pass, passlen, ntpass, ntpasslen, domain)) {
  1709.         DEBUG(1,("password server %s rejected the password\n", cli.desthost));
  1710.         return False;
  1711.     }
  1712.  
  1713.     /* if logged in as guest then reject */
  1714.     if ((SVAL(cli.inbuf,smb_vwv2) & 1) != 0) {
  1715.         DEBUG(0,("password server %s gave us guest only\n", cli.desthost));
  1716.         return(False);
  1717.     }
  1718.  
  1719.  
  1720.         /*
  1721.          * This patch from Rob Nielsen <ran@adc.com> makes doing
  1722.          * the NetWksaUserLogon a dynamic, rather than compile-time
  1723.          * parameter, defaulting to on. This is somewhat dangerous
  1724.          * as it allows people to turn off this neccessary check,
  1725.          * but so many people have had problems with this that I
  1726.          * think it is a neccessary change. JRA.
  1727.          */
  1728.  
  1729.     if (lp_net_wksta_user_logon()) {
  1730.         DEBUG(3,("trying NetWkstaUserLogon with password server %s\n", cli.desthost));
  1731.             if (!cli_send_tconX(&cli, "IPC$", "IPC", "", 1)) {
  1732.                         DEBUG(0,("password server %s refused IPC$ connect\n", cli.desthost));
  1733.                         return False;
  1734.                 }
  1735.  
  1736.         if (!cli_NetWkstaUserLogon(&cli,user,local_machine)) {
  1737.             DEBUG(0,("password server %s failed NetWkstaUserLogon\n", cli.desthost));
  1738.             cli_tdis(&cli);
  1739.             return False;
  1740.         }
  1741.  
  1742.         if (cli.privilages == 0) {
  1743.             DEBUG(0,("password server %s gave guest privilages\n", cli.desthost));
  1744.             cli_tdis(&cli);
  1745.             return False;
  1746.         }
  1747.  
  1748.         if (!strequal(cli.eff_name, user)) {
  1749.             DEBUG(0,("password server %s gave different username %s\n", 
  1750.                  cli.desthost,
  1751.                  cli.eff_name));
  1752.             cli_tdis(&cli);
  1753.             return False;
  1754.         }
  1755.             cli_tdis(&cli);
  1756.     }
  1757.         else {
  1758.         DEBUG(3,("skipping NetWkstaUserLogon with password server %s\n", cli.desthost));
  1759.         }
  1760.  
  1761.     DEBUG(3,("password server %s accepted the password\n", cli.desthost));
  1762.  
  1763.         cli_ulogoff(&cli);
  1764.  
  1765.     return(True);
  1766. }
  1767.  
  1768.  
  1769.